<?php

namespace app\admin\controller\bill;

use app\admin\controller\Common;
use app\admin\model\BillWater as WaterModel;
use app\admin\model\BillElectricity as ElectricityModel;
use app\admin\model\HouseProperty as PropertyModel;
use app\admin\model\HouseNumber as NumberModel;
use app\admin\model\DetailElectricity as DetailModel;
use app\admin\library\Property;
use app\admin\model\BillSum as SumModel;

class Electricity extends Common
{
    public function index()
    {
        $loginUser = $this->auth->getLoginUser();
        $house_property_id = Property::getProperty($loginUser['id']);
        $properties = PropertyModel::where('admin_user_id', $loginUser['id'])->all();
        $this->assign('properties', $properties);
        $this->assign('house_property_id', $house_property_id);
        return $this->fetch();
    }

    //主页面 主表查询
    public function queryElectricity()
    {
        $loginUser = $this->auth->getLoginUser();
        $house_property_id = $this->request->param('house_property_id/d', Property::getProperty($loginUser['id']));
        $conditions = array(
            ['a.house_property_id', '=', $house_property_id]
        );
        $type = $this->request->param('type/s', '', 'trim');
        if ($type) {
            \array_push($conditions, ['a.type', '=', $type]);
        }
        $electricity = ElectricityModel::where($conditions)
        ->alias('a')
        ->join('HouseProperty b', 'a.house_property_id = b.id')
        ->field('a.*, b.name as property_name')
        ->select();
        return $this->returnLayui($electricity);
    }

    //主表 新增
    public function electricity()
    {
        $id = $this->request->param('id/d', 0);
        $house_property_id = $this->request->param('house_property_id/d', 0);
        $property = PropertyModel::get($house_property_id);
        $data = [
            'house_property_id' => $house_property_id,
            'house_property_name' => '',
            'type' => 'C',
            'house_number_id' => [],
        ];
        if ($id) {
            if (!$data = ElectricityModel::get($id)) {
                $this->error('记录不存在。');
            }
            if ($data['house_number_id'] != '') {
                $data['house_number_id'] = explode(",", $data['house_number_id']);
            } else {
                $data['house_number_id'] = [];
            }
            $data['house_property_name'] = $property['name'];
        }
        $loginUser = $this->auth->getLoginUser();
        $property = PropertyModel::where('admin_user_id', $loginUser['id'])->all();
        $number = NumberModel::where('house_property_id', $house_property_id)->order('name')->all();
        $this->assign('property', $property);
        $this->assign('number', $number);
        $this->assign('data', $data);
        $this->assign('id', $id);
        return $this->fetch();
    }

    //主表保存
    public function saveElectricity()
    {
        $id = $this->request->post('id/d', 0);
        $house_property_id = $this->request->post('house_property_id/s', '', 'trim');
        $name = PropertyModel::get($house_property_id)['name'];
        $type = $this->request->post('type/s', '', 'trim') ;
        $name .= $type == 'B' ? '-电费' : '-水费';
        $data = [
            'house_property_id' => $house_property_id,
            'house_number_id' => $this->request->post('house_number_id/s', '', 'trim'),
            'type' => $type,
            'name' => $name,
        ];
        if ($id) {
            if (!$electricity = ElectricityModel::get($id)) {
                $this->error('修改失败，记录不存在。');
            }
            $electricity->save($data);
            $this->success('修改成功。');
        }
        ElectricityModel::create($data);
        $this->success('添加成功。');
    }

    //主页面 明细表查询
    public function queryWater()
    {
        $page = $this->request->param('page/d', LAYUI_PAGE);
        $limit = $this->request->param('limit/d', LAYUI_LIMIT);
        $loginUser = $this->auth->getLoginUser();
        $house_property_id = $this->request->param('house_property_id/d', Property::getProperty($loginUser['id']));
        $conditions = array(
            ['b.house_property_id', '=', $house_property_id]
        );
        $type = $this->request->param('type/s', '', 'trim');
        if ($type) {
            \array_push($conditions, ['b.type', '=', $type]);
        }
        $count = WaterModel::alias('a')
        ->join('BillElectricity b', 'a.bill_electricity_id = b.id')
        ->where($conditions)
        ->count();
        $water = WaterModel::alias('a')
        ->join('BillElectricity b', 'a.bill_electricity_id = b.id')
        ->where($conditions)
        ->order(['a.end_month'=>'desc', 'b.type'])
        ->field('a.id, a.received_mark, date_format( a.end_month, "%Y-%m" ) as end_month,a.end_month as end_month2, a.start_month, b.id as electricity_id, b.type, b.house_property_id, b.name as electricity_name, a.master_sum, a.master_dosage')
        ->page($page, $limit)
        ->select();
        $result = [];
        foreach ($water as  $value) {
            $detail = DetailModel::where('id', $value['electricity_id'])
            ->where('type', $value['type'])
            ->where('month', 'between time', [$value['start_month'], $value['end_month2']])
            ->field('sum(sum) as sum, sum(dosage) as dosage')
            ->select()->toArray();
            if (count($detail)) {
                $value['detail_sum'] = $detail[0]['sum'];
                $value['detail_dosage'] = $detail[0]['dosage'];
            }
            \array_push($result, $value);
        }
        return $this->returnLayui($result, $count);
    }

    // 新增/修改 明细表
    public function water()
    {
        $id = $this->request->param('id/d', 0);
        $house_property_id = $this->request->param('house_property_id/d', 0);
        $electricity = ElectricityModel::where('house_property_id', $house_property_id)->select();
        $data = [
            'bill_electricity_id' => 0,
            'start_month' => '',
            'end_month' => '',
            'master_dosage' => '',
            'master_sum' => '',
        ];
        if ($id) {
            if (!$data = WaterModel::get($id)) {
                $this->error('记录不存在。');
            }
        }
        $this->assign('electricity', $electricity);
        $this->assign('data', $data);
        $this->assign('id', $id);
        return $this->fetch();
    }

    //明细表保存
    public function saveWater()
    {
        $id = $this->request->post('id/d', 0);
        $data = [
                'bill_electricity_id' => $this->request->param('bill_electricity_id/d', 0),
                'received_mark' => 'N',
                'start_month' => $this->request->post('start_month/s', '', 'trim') . '-01',
                'end_month' => $this->request->post('end_month/s', '', 'trim') . '-01',
                'master_dosage' => $this->request->param('master_dosage/d', 0),
                'master_sum' => $this->request->param('master_sum/f', 0.0),
            ];
        if ($id) {
            if (!$water = WaterModel::get($id)) {
                $this->error('修改失败，记录不存在。');
            }
            $water->save($data);
            $this->success('修改成功。');
        }
        WaterModel::create($data);
        $this->success('添加成功。');
    }

    //主表删除
    public function delElectricity()
    {
        $id = $this->request->param('id/d', 0);
        if (!$electricity = ElectricityModel::get($id)) {
            $this->error('删除失败,记录不存在。');
        }
        if (WaterModel::where('bill_electricity_id', $id)->count() > 0) {
            $this->error('删除失败,存在明细记录。');
        }
        $electricity->delete();
        $this->success('删除成功');
    }

    public function delWater()
    {
        $id = $this->request->param('id/d', 0);
        if (!$water = WaterModel::get($id)) {
            $this->error('删除失败,记录不存在。');
        }
        $water->delete();
        $this->success('删除成功');
    }

    public function account()
    {
        $id = $this->request->param('id/d', 0);
        if (!$water = WaterModel::get($id)) {
            $this->error('到账失败,记录不存在。');
        }
        $water->save(['received_mark' => 'Y']);
        //总表记录
        $data = WaterModel::where('a.id', $id)->alias('a')
        ->join('BillElectricity b', 'a.bill_electricity_id = b.id')
        ->field('b.type, b.house_property_id, a.master_sum')
        ->select()->toArray();
        $sum_data = [
            'house_property_id' => $data[0]['house_property_id'],
            'type' => $data[0]['type'],
            'total_money' => $data[0]['master_sum'],
            'accounting_date' => date('Ymd')
        ];
        SumModel::create($sum_data);
        $this->success('操作成功');
    }
}
